package com.benzhitech.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * 资源加载工具类
 */
public class ResourceUtil {

    private static final Logger log = LoggerFactory.getLogger(ResourceUtil.class);

    /**
     * 列出类路径下的所有资源
     */
    public static void listResources(String path) {
        ClassLoader classLoader = ResourceUtil.class.getClassLoader();
        log.info("列出类路径资源: {}, ClassLoader: {}", path, classLoader);
        
        try {
            // 获取类路径下的资源 URL
            Enumeration<URL> resources = classLoader.getResources(path);
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                log.info("找到资源: {}", url);
                
                String protocol = url.getProtocol();
                if ("file".equals(protocol)) {
                    // 文件系统资源
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    listFileResources(new File(filePath), path);
                } else if ("jar".equals(protocol)) {
                    // JAR 文件资源
                    String jarPath = url.getPath();
                    if (jarPath.startsWith("file:")) {
                        jarPath = jarPath.substring("file:".length());
                    }
                    
                    int separatorIndex = jarPath.indexOf("!/");
                    if (separatorIndex != -1) {
                        jarPath = jarPath.substring(0, separatorIndex);
                    }
                    
                    jarPath = URLDecoder.decode(jarPath, "UTF-8");
                    listJarResources(jarPath, path);
                }
            }
        } catch (IOException e) {
            log.error("列出类路径资源时发生错误: {}", path, e);
        }
    }
    
    /**
     * 列出文件系统中的资源
     */
    private static void listFileResources(File directory, String basePath) {
        if (!directory.exists() || !directory.isDirectory()) {
            log.warn("目录不存在或不是目录: {}", directory.getAbsolutePath());
            return;
        }
        
        log.info("扫描目录: {}", directory.getAbsolutePath());
        File[] files = directory.listFiles();
        if (files != null) {
            for (File file : files) {
                String relativePath = basePath.endsWith("/") ? basePath + file.getName() : basePath + "/" + file.getName();
                
                if (file.isDirectory()) {
                    listFileResources(file, relativePath);
                } else {
                    log.info("  - 文件: {}", relativePath);
                }
            }
        }
    }
    
    /**
     * 列出 JAR 文件中的资源
     */
    private static void listJarResources(String jarPath, String basePath) {
        log.info("扫描 JAR 文件: {}", jarPath);
        
        try (JarFile jarFile = new JarFile(jarPath)) {
            Enumeration<JarEntry> entries = jarFile.entries();
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();
                
                if (name.startsWith(basePath)) {
                    log.info("  - JAR 条目: {}", name);
                }
            }
        } catch (IOException e) {
            log.error("扫描 JAR 文件时发生错误: {}", jarPath, e);
        }
    }
    
    /**
     * 检查资源是否存在
     */
    public static boolean resourceExists(String resourcePath) {
        // 去掉前导斜杠以符合 classpath 资源习惯
        if (resourcePath.startsWith("/")) {
            resourcePath = resourcePath.substring(1);
        }
        
        URL url = ResourceUtil.class.getClassLoader().getResource(resourcePath);
        boolean exists = url != null;
        log.info("检查资源是否存在: {} -> {}", resourcePath, exists);
        
        if (exists) {
            log.info("资源 URL: {}", url);
        }
        
        return exists;
    }
} 